<template>
  <!-- 菜单分组 -->
  <div class="app-container">
    <el-form class="search-form-new" :model="queryParams" ref="queryForm" v-show="showSearch" :inline="true">
      <el-form-item label="分组名称" prop="groupName">
        <el-input v-model="queryParams.groupName" placeholder="请输入分组名称" clearable />
      </el-form-item>
      <el-form-item label="分组key" prop="groupKey">
        <el-input v-model="queryParams.groupKey" placeholder="请输入分组key" clearable />
      </el-form-item>
      <el-form-item label="服务包" prop="bindServer">
        <el-select v-model="queryParams.bindServer" clearable placeholder="请选择服务包">
          <el-option v-for="item in bindOptions" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select> 
      </el-form-item>
      <!-- <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="分组状态"
          clearable
          size="small"
          style="width: 240px"
        >
          <el-option
            v-for="dict in dict.type.sys_normal_disable"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item> -->
      <!-- <el-form-item label="创建时间">
        <el-date-picker
          v-model="dateRange"
          size="small"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item> -->
      <el-form-item class="btns">
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button type="warning" icon="el-icon-refresh" @click="resetQuery">重置</el-button>
        <el-button type="success" icon="el-icon-plus" @click="handleAdd">新增</el-button>
      </el-form-item>
    </el-form>

    <div class="table_box">
      <el-table stripe v-loading="loading" :data="roleList" @selection-change="handleSelectionChange">
        <!-- <el-table-column type="selection" width="55" align="center" /> -->
        <el-table-column label="分组编号" prop="groupId" width="100" />
        <el-table-column label="分组名称" prop="groupName" />
        <el-table-column label="分组key" prop="groupKey" />
          <el-table-column label="服务包" prop="">
          <template slot-scope="scope">
            <span>{{ bindServeFilter(scope.row.bindServer) }}</span>
          </template>
        </el-table-column>
          <el-table-column label="服务类型" prop="">
          <template slot-scope="scope">
            <span>{{ bindCategoryFilter(scope.row.category) }}</span>
          </template>
        </el-table-column>

        <el-table-column label="计费方式" prop="">
          <template slot-scope="scope">
            <span>{{ commonMaps.buyWayMap[scope.row.buyWay].label }}</span>
          </template>
        </el-table-column>
        <el-table-column label="起开时长" prop="minMonthDuration" />
        <el-table-column label="开通虞豆" prop="monthAmount" />

        <el-table-column label="备注" prop="remark" />
        <el-table-column label="是否展示" align="center" width="100">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.status" active-value="0" inactive-value="1"
              @change="handleStatusChange($event, scope.row.groupId)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="160">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding " width="300">
          <template slot-scope="scope">
            <el-button type="edit" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
            <el-button type="del" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>

            <el-button type="edit" icon="el-icon-edit" @click="openGroupInfo(scope.row.groupId)">分组详情</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
        @pagination="getList" />
    </div>

    <!-- 添加或修改分组配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="form" class="form-box" label-position="right" :inline="true" :model="form" :rules="rules"
        label-width="100px">
        <el-form-item label="分组名称" prop="groupName">
          <el-input v-model="form.groupName" placeholder="请输入分组名称" />
        </el-form-item>
        <el-form-item prop="groupKey">
          <span slot="label">
            <el-tooltip content="用于控制权限，禁止修改" placement="top">
              <i class="el-icon-question"></i>
            </el-tooltip>
            分组key
          </span>
          <el-input v-model="form.groupKey" placeholder="请输入权限字符" />
        </el-form-item>
        <el-form-item prop="buyWay">
          <span slot="label">
            <el-tooltip content="控制该接口渠道开通时一次性永久开通，还是按时长开通，修改该参数不影响已开通的用户。" placement="top">
              <i class="el-icon-question"></i>
            </el-tooltip>
            计费方式
          </span>
          <el-radio-group v-model="form.buyWay">
            <el-radio v-for="(item, key) in commonMaps.buyWayMap" :key="key" :label="key">{{ item.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="minMonthDuration" v-if="form.buyWay == 2">
          <span slot="label">
            <el-tooltip content="控制该分组开通时最低开通月数。" placement="top">
              <i class="el-icon-question"></i>
            </el-tooltip>
            起开时长
          </span>
          <el-input-number style="width:150px" v-model="form.minMonthDuration" placeholder="最低开通月数" />月
        </el-form-item>
        <el-form-item prop="monthAmount" label="开通虞豆">
          <el-input type="number" v-model="form.monthAmount" placeholder="开通该功能多少虞豆，计费方式为月租时填写一个月的费用"
            @change="monthAmountChange" />
        </el-form-item>
        <el-form-item prop="renewalAmount" label="续费虞豆" v-show="form.buyWay == 2">
          <el-input type="number" v-model="form.renewalAmount" placeholder="续费时每个月多少虞豆" />
        </el-form-item>

        <el-form-item label="绑定服务" prop="">
          <el-select v-model="form.bindServer" clearable placeholder="请选择服务包">
            <el-option v-for="item in bindOptions" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item><br />

         <el-form-item label="服务类型" prop="category">
          <el-select v-model="form.category" clearable placeholder="请选择服务类型">
            <el-option v-for="item in categoryOptions" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item><br />
        <!-- <el-form-item label="分组顺序" prop="roleSort">
          <el-input-number v-model="form.roleSort" controls-position="right" :min="0" />
        </el-form-item> -->
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio v-for="dict in dict.type.sys_normal_disable" :key="dict.value"
              :label="dict.value">{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item><br />
        <el-form-item label="备注">
          <el-input style="width:600px" v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
        </el-form-item><br />
        <el-form-item label="菜单权限">
          <el-checkbox v-model="menuExpand" @change="handleCheckedTreeExpand($event, 'menu')">展开/折叠</el-checkbox>
          <el-checkbox v-model="menuNodeAll" @change="handleCheckedTreeNodeAll($event, 'menu')">全选/全不选</el-checkbox>
          <!-- <el-checkbox v-model="form.menuCheckStrictly" @change="handleCheckedTreeConnect($event, 'menu')">父子联动</el-checkbox> -->
          <el-tree class="tree-border" :data="menuOptions" :check-on-click-node="true" show-checkbox ref="menu"
            node-key="id" :check-strictly="true" empty-text="加载中，请稍候" :props="defaultProps"></el-tree>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">

        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>

    <editGroupInfo ref="editGroupInfo"></editGroupInfo>
  </div>
</template>

<script>
import {
  menuGroupList,
  getMenuGroupDetail,
  addMenuGroup,
  editMenuGroup,
  delMenuGroup,
  updateStatus,
} from "@/api/system/menuGroup.js";
import { treeselect as menuTreeselect } from "@/api/system/menu";
import editGroupInfo from "./editGroupInfo.vue";
export default {
  name: "MenuGroup",
  dicts: ["sys_normal_disable"],
  components: { editGroupInfo },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      bindOptions: [{
        value: 1,
        label: '基础服务包'
      }, {
        value: 2,
        label: '商城服务包'
      }],

      categoryOptions: [{
        value: 1,
        label: '基础服务分类'
      }, {
        value: 2,
        label: '商城服务分类'
      }],
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 分组表格数据
      roleList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示弹出层（数据权限）
      openDataScope: false,
      menuExpand: false,
      menuNodeAll: false,
      deptExpand: true,
      deptNodeAll: false,
      // 日期范围
      dateRange: [],
      // 菜单列表
      menuOptions: [],
      // 部门列表
      deptOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        roleName: undefined,
        roleKey: undefined,
        status: undefined,
      },
      // 表单参数
      form: {
        buyWay: "",
        renewalAmount: '',
        bindServer: "",
      },
      defaultProps: {
        children: "children",
        label: "label",
      },
      // 表单校验
      rules: {
        groupName: [
          { required: true, message: "分组名称不能为空", trigger: "blur" },
        ],
        groupKey: [
          { required: true, message: "分组key不能为空", trigger: "blur" },
        ],
        buyWay: [
          { required: true, message: "计费方式不能为空", trigger: "change" },
        ],
        bindServer: [
          { required: true, message: "绑定服务不能为空", trigger: "change" },
        ],
        monthAmount: [
          { required: true, message: "费用不能为空", trigger: "change" },
        ],
        renewalAmount: [
          { required: true, message: "续费虞豆不能为空", trigger: "change" },
        ],
        minMonthDuration: [
          {
            required: true,
            message: "最低开通时长不能为空",
            trigger: "change",
          },
        ],
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    bindServeFilter(val) {
      if(val == 1) {
        return "基础服务包";
      }
      if(val == 2) {
        return "商城服务包";
      }
      return ''
    },
       bindCategoryFilter(val) {
      if(val == 1) {
        return "基础服务分类";
      }
      if(val == 2) {
        return "商城服务分类";
      }
      return '其他'
    },
    // 打开分组详情弹窗
    openGroupInfo(groupId) {
      this.$refs.editGroupInfo.open(groupId);
    },

    /** 查询分组列表 */
    getList() {
      this.loading = true;
      menuGroupList(this.queryParams).then((response) => {
        this.roleList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询菜单树结构 */
    getMenuTreeselect() {
      menuTreeselect().then((response) => {
        this.menuOptions = response.data;
      });
    },
    // 所有菜单节点数据
    getMenuAllCheckedKeys() {
      // 目前被选中的菜单节点
      let checkedKeys = this.$refs.menu.getCheckedKeys();
      // 半选中的菜单节点
      let halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys();
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      return checkedKeys;
    },
    //  开通虞豆改变
    monthAmountChange(e) {
      console.log("%c Line:296 🍌 e", "color:#93c0a4", e);
      this.$set(this.form, "renewalAmount", e);
    },
    // 分组状态修改
    handleStatusChange(e, groupId) {
      updateStatus({
        status: e,
        groupId,
      }).then((res) => {
        console.log("%c Line:312 🍌 res", "color:#93c0a4", res);
        this.getList();
      });
      // let text = row.status === "0" ? "启用" : "停用";
      // this.$modal.confirm('确认要"' + text + '""' + row.roleName + '"分组吗？').then(function() {
      //   return changeRoleStatus(row.groupId, row.status);
      // }).then(() => {
      //   this.$modal.msgSuccess(text + "成功");
      // }).catch(function() {
      //   row.status = row.status === "0" ? "1" : "0";
      // });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 取消按钮（数据权限）
    cancelDataScope() {
      this.openDataScope = false;
      this.reset();
    },
    // 表单重置
    reset() {
      if (this.$refs.menu != undefined) {
        this.$refs.menu.setCheckedKeys([]);
      }
      (this.menuExpand = false),
        (this.menuNodeAll = false),
        (this.deptExpand = true),
        (this.deptNodeAll = false),
        (this.form = {
          groupId: undefined,
          groupName: undefined,
          groupKey: undefined,
          status: "0",
          bindServer: '',
          menuIds: [],
          deptIds: [],
          menuCheckStrictly: true,
          deptCheckStrictly: true,
          remark: undefined,
          buyWay: "",
          monthAmount: "",
          minMonthDuration: "",
        });
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.groupId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    // 树权限（展开/折叠）
    handleCheckedTreeExpand(value, type) {
      if (type == "menu") {
        let treeList = this.menuOptions;
        for (let i = 0; i < treeList.length; i++) {
          this.$refs.menu.store.nodesMap[treeList[i].id].expanded = value;
        }
      } else if (type == "dept") {
        let treeList = this.deptOptions;
        for (let i = 0; i < treeList.length; i++) {
          this.$refs.dept.store.nodesMap[treeList[i].id].expanded = value;
        }
      }
    },
    // 树权限（全选/全不选）
    handleCheckedTreeNodeAll(value, type) {
      if (type == "menu") {
        this.$refs.menu.setCheckedNodes(value ? this.menuOptions : []);
      } else if (type == "dept") {
        this.$refs.dept.setCheckedNodes(value ? this.deptOptions : []);
      }
    },
    // 树权限（父子联动）
    handleCheckedTreeConnect(value, type) {
      if (type == "menu") {
        this.form.menuCheckStrictly = value ? true : false;
      } else if (type == "dept") {
        this.form.deptCheckStrictly = value ? true : false;
      }
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getMenuTreeselect();
      this.open = true;
      this.title = "添加分组";
      this.$set(this.form, "buyWay", "2");
      this.form.minMonthDuration = 1;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      const groupId = row.groupId || this.ids;
      this.reset();
      getMenuGroupDetail(groupId).then((response) => {
        this.form = response.data;
        if (this.form.buyWay) this.form.buyWay = String(this.form.buyWay);

        this.form.menuCheckStrictly = true;
        this.menuOptions = this.form.menusAllTree;
        let checkedKeys = this.form.menuIds;
        this.open = true;
        this.$nextTick(() => {
          checkedKeys.forEach((v) => {
            this.$nextTick(() => {
              this.$refs.menu.setChecked(v, true, false);
            });
          });
        });
        this.title = "修改分组";
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          // this.form
          // console.log("%c Line:463 🍐 this.form", "color:#465975", this.form);
          if (this.form.groupId != undefined) {
            this.form.menuIds = this.getMenuAllCheckedKeys();
            editMenuGroup(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.form.menuIds = this.getMenuAllCheckedKeys();
            addMenuGroup(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const groupIds = row.groupId || this.ids;
      this.$modal
        .confirm('是否确认删除分组编号为"' + groupIds + '"的数据项？')
        .then(function () {
          return delMenuGroup(groupIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep .form-box .el-form-item__content {
  width: 260px !important;
}

::v-deep .form-box .el-radio-group {
  width: 300px;
}

::v-deep .form-box .el-input {
  width: auto;
}
</style>